package cn.gowss.judger.core;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class StreamGobbler extends Thread {
    private static Logger logger = LoggerFactory.getLogger(StreamGobbler.class);
    private InputStream inputStream;
    @SuppressWarnings("unused")
	private String streamType;
    private String outputFilePath;
    private StringBuilder buf;
    private volatile boolean isStopped = false;

    /**
     * @param inputStream the InputStream to be consumed
     * @param streamType  the stream type (should be OUTPUT or ERROR)
     */
    public StreamGobbler(final InputStream inputStream, final String streamType, final String outputFilePath) {
        this.inputStream = inputStream;
        this.streamType = streamType;
        this.outputFilePath =outputFilePath;
        this.buf = new StringBuilder();
        this.isStopped = false;
    }

    /**
     * Consumes the output from the input stream and displays the lines consumed
     * if configured to do so.
     */
    @Override
    public void run() {
    	try {
    		File writeName = new File(outputFilePath); // 相对路径，如果没有则要建立一个新的output.txt文件
    		writeName.createNewFile();// 创建新文件,有同名的文件的话直接覆盖
			FileUtils.copyInputStreamToFile(inputStream, writeName);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			this.isStopped = true;
            synchronized (this) {
                notify();
            }
		}
    }

    public String getContent() {
        if (!this.isStopped) {
            synchronized (this) {
                try {
                    wait();
                } catch (InterruptedException ignore) {
                    ignore.printStackTrace();
                }
            }
        }
        return this.buf.toString();
    }
    
}
